//
//  ChangePasswordViewController.m
//  HuaMuJinRong
//
//  Created by 吴建东 on 16/2/26.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "ChangePasswordViewController.h"
#import "CommonClass.h"
#import "SGFindPassWordBackViewController.h"

@interface ChangePasswordViewController ()<HTTPClientDelegate>
@property (weak, nonatomic) IBOutlet UILabel *oldPwdLabel;
@property (weak, nonatomic) IBOutlet UITextField *oldPwdTextField;
@property (weak, nonatomic) IBOutlet UIView *oldPwdView;
@property (strong, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UIView *firstPwdView;
@property (weak, nonatomic) IBOutlet UILabel *firstPwdLabel;
@property (weak, nonatomic) IBOutlet UITextField *firstPwdTextField;
@property (weak, nonatomic) IBOutlet UIView *surePwdView;
@property (weak, nonatomic) IBOutlet UILabel *surePwdLabel;
@property (weak, nonatomic) IBOutlet UITextField *surePwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *sureButton;
@property (weak, nonatomic) IBOutlet UIButton *forgetPwdButton;

@property (nonatomic ,strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL isLoading;
@end

@implementation ChangePasswordViewController
#pragma mark - Life Cycle
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
  
    [self initNavBarTitle:self.naviTitle andLeftItemName:@"返回" andRightItemName:@""];
    
    [self initView];
    
    if (self.editType == ChangeTradePwd) {
        _firstPwdLabel.text = @"交易密码";
        _oldPwdView.hidden = YES;
        _forgetPwdButton.hidden = YES;
    }else {
        _firstPwdLabel.text = @"登录密码";
        _oldPwdView.hidden = NO;
        _forgetPwdButton.hidden = NO;
    }
    [_oldPwdTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    [_firstPwdTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    [_surePwdTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    _oldPwdTextField.secureTextEntry = YES;
    _firstPwdTextField.secureTextEntry = YES;
    _surePwdTextField.secureTextEntry = YES;
}

- (void)backClick {
    if (self.editType == ChangeTradePwd) {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 4] animated:YES];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
  
}

#pragma mark - Action
- (IBAction)forgetPwdButtonClick:(id)sender {
    SGFindPassWordBackViewController *findPassWordBackVC=[[SGFindPassWordBackViewController alloc] initWithNibName:@"SGFindPassWordBackViewController" bundle:nil];
    [self.navigationController pushViewController:findPassWordBackVC animated:YES];
}

- (IBAction)sureButtonClick:(id)sender {
    if ([_firstPwdTextField.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请输入新密码"];
        return;
    }
    if ([_surePwdTextField.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请再次输入新密码"];
        return;
    }
    if (![_firstPwdTextField.text isEqualToString:_surePwdTextField.text]) {
        [SVProgressHUD showImage:nil status:@"两次输入的新密码不一致"];
        return;
    }
    
    if (self.editType == ChangeLoginPwd) {
        if ([_oldPwdTextField.text isEqualToString:@""]) {
            [SVProgressHUD showImage:nil status:@"原密码不能为空"];
            return;
        }
        
        if ([_oldPwdTextField.text isEqualToString:_surePwdTextField.text]) {
            [SVProgressHUD showImage:nil status:@"新密码不能与原密码一致"];
            return;
        }
    }
    
    [self keyBoardHidden];
    [self changeRequest];
}

- (void)changeValue:(UITextField *)textField {
    if (self.editType == ChangeLoginPwd) {
        if (_firstPwdTextField.text.length>=6 && _surePwdTextField.text.length>=6 && _oldPwdTextField.text.length>0) {
            [CommonClass buttonEnableWithButton:_sureButton enable:YES];
        }else {
            [CommonClass buttonEnableWithButton:_sureButton enable:NO];
        }
    }else {
        if (_firstPwdTextField.text.length >= 6 && _surePwdTextField.text.length>=6) {
            [CommonClass buttonEnableWithButton:_sureButton enable:YES];
        }else {
            [CommonClass buttonEnableWithButton:_sureButton enable:NO];
        }
    }
}

- (void)keyBoardHidden {
    [_firstPwdTextField resignFirstResponder];
    [_surePwdTextField resignFirstResponder];
    [_oldPwdTextField resignFirstResponder];
}

#pragma mark - Data
- (void)changeRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍后再试"];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if (self.editType == ChangeLoginPwd) {
        [parameters setObject:@"105" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
        [parameters setObject:[NSString encrypt3DES:_oldPwdTextField.text key:DESkey] forKey:@"oldloginpwd"];
        [parameters setObject:[NSString encrypt3DES:_surePwdTextField.text key:DESkey] forKey:@"newloginpwd"];
    }else {
        [parameters setObject:@"104" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
        //[parameters setObject:[NSString encrypt3DES:_oldPwdTextField.text key:DESkey] forKey:@"currentdealpwd"];
        [parameters setObject:[NSString encrypt3DES:_surePwdTextField.text key:DESkey] forKey:@"newdealpwd"];
    }
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma HTTPClientDelegate 网络数据回调代理
-(void) startRequest {
    _isLoading = YES;
}

// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    [SVProgressHUD dismiss];
    NSDictionary *dics = obj;
    // DLOG(@"===%@=======", dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@", [obj objectForKey:@"msg"]]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.editType == ChangeTradePwd) {
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 4] animated:YES];
            }else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        });
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        // 服务器返回数据异常
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [obj objectForKey:@"msg"]]];
    }
}

// 返回失败
-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    // 服务器返回数据异常
    //    [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后再试"]
    [SVProgressHUD dismiss];
}

// 无可用的网络
-(void) networkError {
    _isLoading = NO;
    [SVProgressHUD dismiss];
    // 服务器返回数据异常
//    [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
}

#pragma mark - View
- (void)initView {
    
    self.sureButton.layer.cornerRadius = kCornerRadius;
    [CommonClass buttonEnableWithButton:_sureButton enable:NO];
    _sureButton.titleLabel.font = KFontSize(15);
    _oldPwdLabel.font = KFontSize(14);
    _oldPwdTextField.font = KFontSize(14);
    _firstPwdLabel.font = KFontSize(14);
    _firstPwdTextField.font = KFontSize(14);
    _surePwdLabel.font = KFontSize(14);
    _surePwdTextField.font = KFontSize(14);
    _forgetPwdButton.titleLabel.font = KFontSize(14);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
